//------------------------------------------------------------------------------
// <copyright company="Telligent Systems">
//     Copyright (c) Telligent Systems Corporation.  All rights reserved.
// </copyright> 
//------------------------------------------------------------------------------

using System;
using System.Collections;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using CommunityServer.Components;
using CommunityServer.Configuration;
using CommunityServer.ControlPanel.UI;
using CommunityServer.Galleries;
using CommunityServer.Galleries.Components;
using CommunityServer.Galleries.Controls;
using CA = ComponentArt.Web.UI;
using ResourceManager = CommunityServer.ControlPanel.Components.ResourceManager;

namespace CommunityServer.ControlPanel.Photos
{
	/// <summary>
	///		Summary description for PostListControl.
	/// </summary>
	public class PostListControl : BaseGalleryGridControl
	{
		protected CommunityServer.ControlPanel.Controls.ResourceControl Resourcecontrol1;

		#region Child Controls

		protected ParentCategoryDropDown CategoryList;
		protected LinkButton New;
		protected CommunityServer.ControlPanel.Controls.ResourceControl FeedbackFilterLabel;
		protected HtmlInputFile PictureData;
		protected CA.Grid Grid1;

		#endregion
		protected System.Web.UI.WebControls.RegularExpressionValidator AttachmentDataValidator;

		protected int categoryID = CSContext.Current.GetIntFromQueryString("cid",-1);

		private bool HasCategoryIDFilter
		{
			get{return categoryID != -1;}
		}

		private void Page_Load(object sender, EventArgs e)
		{

			//overload the row size because this is a two line grid
			this.CurrentGridRowSize = 2;

			AttachmentDataValidator.Text = string.Concat(ResourceManager.GetString("CP_Photos_Attachment_UploadAttachment_InvlalidFileType"),"&nbsp;");
			AttachmentSettings fs = GalleryConfiguration.Instance().AttachmentSettings;
			AttachmentDataValidator.ValidationExpression = fs.ValidationPattern;

			//Add some autopostback action to the quickadd
			PictureData.Attributes.Add("onchange", Page.GetPostBackEventReference(PictureData));

			if(!Page.IsPostBack && !GalleryPage.IsCallBack)
			{
				BindFilters(); //Populate the Category drop list
				ConfigurePage();//Select the Category in the drop list

				buildGrid();
				Grid.DataBind();
			}
			else
			{
				SetGridMode();
				
				//check to see if our quick add has data
				if((PictureData != null) && (PictureData.PostedFile != null) && (PictureData.PostedFile.ContentLength > 0))
					QuickAddPicture();

			}
		}

		private void SetGridMode()
		{
			if(HasCategoryIDFilter)
				this.GridMode = CA.GridRunningMode.Client;
			else
				this.GridMode = CA.GridRunningMode.Callback;    
		}

		private void DeletePicture(int postID)
		{
			if(postID > 0)
			{
				GalleryPost p = GalleryPosts.GetPicture(postID);
				if(p != null)
					GalleryPosts.DeletePicture(p) ;
			}
		}

		private void QuickAddPicture()
		{
			Page.Validate();
			if(!Page.IsValid)
				return;

			GalleryPost post = new GalleryPost();
			post.Username = CSContext.Current.User.Username;
			post.SectionID = CurrentGallery.SectionID;
			post.ParentID = 0;
			post.GalleryPostType = GalleryPostType.Image;
			post.PostID = -1;

			post.Subject = "";
			post.Excerpt = "";
			post.Body = "";
			post.PostType = PostContentType.HTML;
			post.FormattedBody = null;


			ArrayList al = new ArrayList();
			int cid = Globals.SafeInt(CategoryList.SelectedValue, -1);
			if(cid > -1)
				al.Add(CategoryList.SelectedItem.Text);
 
			post.Categories = (string[]) al.ToArray(typeof (string));

			post.PostDate = DateTime.Now;
			post.UserTime = UserTime.ConvertToUserTime(post.PostDate);

			// Create the picture in the database
			GalleryPosts.CreatePicture(CurrentGallery.SectionID, post, new PostAttachment(PictureData.PostedFile));

			//make the thumbnail
			ImageHandling.ScalePicture(post, CurrentGallery.GetThumbnailSettings());

			//Response redirect to make sure the user doesnt give us back button trouble
			string postListURL = Globals.AppendQuerystring(GalleryUrls.Instance().ControlPanel_Photos_PostList , string.Concat("cid=",cid.ToString())) ;
			Response.Redirect(postListURL) ;
			
		}
		private void BindFilters()
		{
			ArrayList al = PostCategories.GetCategories(CurrentGallery.SectionID, false, true, -1);
			foreach(PostCategory pc in al)
			{
				CategoryList.Items.Add(new ListItem(pc.Name,pc.CategoryID.ToString()));
			}
			CategoryList.Items.Insert(0,new ListItem(ResourceManager.GetString("CP_Photos_CategoryFilterAll"),"-1"));
		}

		private void ConfigurePage()
		{

			ListItem li = CategoryList.Items.FindByValue(categoryID.ToString());
			if(li != null)
				li.Selected = true;

			SetGridMode();
              
 		}

		protected override void buildGrid()
		{
			GalleryThreadQuery query = new GalleryThreadQuery();
			query.SectionID = CurrentGallery.SectionID;
			
			// Show posts for an inactive section if the user is an admin
			CSContext cntx = CSContext.Current;
			query.RequireSectionIsActive = !(cntx.User.IsGalleryAdministrator || cntx.User.IsAdministrator);

			if(HasCategoryIDFilter)
				query.CategoryID = categoryID;

			query.ApplicationPostType = GalleryPostType.Image;

			if(this.GridMode == CA.GridRunningMode.Callback)
			{
				query.PageSize = this.DefaultPageSize;
				query.PageIndex = Grid.CurrentPageIndex;
				Grid.ManualPaging = true;
			}
			else
			{
				query.PageSize = int.MaxValue;
				Grid.ManualPaging = false;
			}

			query.SortBy = GalleryThreadSortBy.ThreadDate;
			query.SortOrder = SortOrder.Descending;
            

			ThreadSet ts = GalleryPosts.GetPictures(query, false);
			
			Grid.DataSource = ts.Threads;

			this.RecordCount = ts.TotalRecords;

			base.buildGrid();

		}

		protected override void ConfigureGrid()
		{
			AddGridCheckMarkTemplate("IsApproved");
			string postEditorURL = Globals.AppendQuerystring(GalleryUrls.Instance().ControlPanel_Photos_NewPost() ,@"sectionid=##  DataItem.GetMember(""SectionID"").Text ##&PostID=## DataItem.GetMember(""PostID"").Text ##", true);
			AddGridHrefTemplate(postEditorURL, "Subject") ;
			string commentListURL = Globals.AppendQuerystring(GalleryUrls.Instance().ControlPanel_Photos_CommentList ,@"pid=## DataItem.GetMember(""PostID"").Text ##", true);
			AddGridHrefTemplate(commentListURL, "Replies") ;
			AddGridPublishedDateTemplate("AuthorUrl", "DisplayName", "PostDate");
			AddGridPagerTemplate("Subject", "Username", "PostDate", "IsApproved", "ThumbnailURL");

			string referralURL = "referrals.aspx?sectionid=## DataItem.GetMember('SectionID').Text ##&pid=## DataItem.GetMember('PostID').Text ##";
			AddGridHrefTemplate(referralURL, "Views") ;
		}

		#region Web Form Designer generated code
		override protected void OnInit(EventArgs e)
		{
			//
			// CODEGEN: This call is required by the ASP.NET Web Form Designer.
			//
			base.OnInit(e);
			InitializeComponent();
			this.Grid.DeleteCommand += new CA.Grid.GridItemEventHandler(this.Grid_DeleteCommand);
			this.CategoryList.SelectedIndexChanged += new EventHandler(this.CategoryList_SelectedIndexChanged);
		}
		
		/// <summary>
		///		Required method for Designer support - do not modify
		///		the contents of this method with the code editor.
		/// </summary>
		private void InitializeComponent()
		{
			this.Load += new System.EventHandler(this.Page_Load);

		}
		#endregion


		private void Grid_DeleteCommand(object sender, CA.GridItemEventArgs e)
		{
			DeletePicture(Globals.SafeInt(e.Item["PostID"].ToString(), 0));
		}

	
		private void CategoryList_SelectedIndexChanged(object sender, EventArgs e)
		{
			//TODO: Figure out how to use a CA filter and dump this hack
			int cid = Globals.SafeInt(CategoryList.SelectedValue, -1); 
			string postListURL = Globals.AppendQuerystring(GalleryUrls.Instance().ControlPanel_Photos_PostList , string.Concat("cid=",cid.ToString())) ;
			Response.Redirect(postListURL) ;
			
			//Grid.CurrentPageIndex = 0;
			//Grid.DataBind();
		
		}
	}
}